﻿using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Threading;
using GurLoader.Service.ImgurTaskBuilder;
using GurLoader.Util;
using GurLoader.View;
using GurLoader.ViewModel;

namespace GurLoader.Service.TaskExecution
{
    public class DefaultTaskExecutionService : ITaskExecutionService
    {
        private Dispatcher CurrentDispatcher { get; set; }
        private IViewBuilder ViewBuilder { get; set; }

        public DefaultTaskExecutionService(Dispatcher currentDispatcher, IViewBuilder viewBuilder)
        {
            if ( currentDispatcher == null )
                throw new ArgumentNullException("currentDispatcher");

            if (viewBuilder == null)
                throw new ArgumentNullException("viewBuilder");

            CurrentDispatcher = currentDispatcher;
            ViewBuilder = viewBuilder;
        }

        public void ExecuteTask(Task<ImgurProcessResult> task, Progress<IDelegatingCommandProgress> progress, CancellationTokenSource cancellationTokenSource, ICommandManager commandManager)
        {
            CurrentDispatcher.BeginInvoke(
                DispatcherPriority.Normal,
                new Action(delegate
                {
                    var viewModel = new GurLoaderViewModel(progress, cancellationTokenSource, commandManager);
                    ViewBuilder.CreateMainWindow(viewModel, true);
                    task.Start();
                }));
        }
    }
}
